<?php
/**
 * Created by PhpStorm.
 * User: tomxia
 * Date: 2017/11/30
 * Time: 18:22
 */
require_once "Tools.php";
class Session
{

    const SESSION_INCREMENT_KEY = "mom_tomxia_session_increment";
    const SESSION_KEY = "mom_tomxia_session_";
    const SESSION_PRIVATE_KEY = "tom_xia";
    const SESSION_EXPIRE_TIME = 24*3600*60;
    

    private $redis;
    private $client_sid;//客户端session_id
    private $server_sid = ""; //服务端session_id
    private $msg = "";
    private $code = "-100";

    protected  function generateNewSession(){
        $num = $this->redis->incr(self::SESSION_INCREMENT_KEY);
        $sid1 = md5($num."~~".time().mt_rand(1000,9999));
        $sid2 = Tools::auth_code($sid1."|".$num."|".mt_rand(10000,99999),"ENCODE",self::SESSION_PRIVATE_KEY);
        $this->server_sid = $sid1;
        $this->client_sid = $sid2;

        $this->redis->hset(self::SESSION_KEY.$this->server_sid,"_____",1);
        $this->redis->expire(self::SESSION_KEY.$this->server_sid,self::SESSION_EXPIRE_TIME);
    }
    /**
     * Session constructor.
     * @param $sid sessionID
     */
    public function __construct(\Redis $redis,$sid=NULL)
    {
        $this->redis = $redis;

        if($sid === NULL){
            $this->generateNewSession();
        }else{
            if(!$this->redis->exists(self::SESSION_KEY.$sid)){
                $this->msg = "session过期";
            }else{
                //延长session时长以便 程序来得及处理
                $this->client_sid = "";
                $this->server_sid = $sid;
            }
        }
    }
    public function set($key,$value=null){
        if($value){
              $this->redis->hset(self::SESSION_KEY.$this->server_sid,$key,$value);
        }else{
            $this->redis->hdel(self::SESSION_KEY.$this->server_sid,$key);
        }
    }
    public function get($key=null){
        if($key){
           return  $this->redis->hget(self::SESSION_KEY.$this->server_sid,$key);
        }else{
            return $this->redis->hgetall(self::SESSION_KEY.$this->server_sid);
        }
    }
    public function get_Sid(){
        return $this->server_sid;
    }
    public function getSid()
    {
        return $this->client_sid;
    }
    public function clear(){
        $this->redis->del(self::SESSION_KEY.$this->server_sid);
    }
    public function getMsg(){
        return $this->msg;
    }
    public function getCode(){
        return $this->code;
    }

}